package com.hc.category3;

import com.hc.common.utils.JsonUtil;
import org.junit.jupiter.api.Test;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author hecai
 * @date 2021/12/9 23:23
 */
public class Category3Demo3 {

    @Test
    public void fun() {
        List<Category> categoryList = DB.init();
        //找到一级分类
        List<Category> res = categoryList.stream()
                .filter(item -> item.getPid() == null)
                .peek(item -> item.setChildren(getChildren(item, categoryList)))
                .sorted((c1, c2) -> c1.getSort() - c2.getSort())
                .collect(Collectors.toList());
        System.out.println(JsonUtil.obj2String(res));
    }

    private List<Category> getChildren(Category category, List<Category> all) {
        List<Category> childList = all.stream()
                .filter(item -> category.getId().equals(item.getPid()))
                .peek(item -> item.setChildren(getChildren(item, all)))
                .sorted(Comparator.comparingInt(Category::getSort))
                .collect(Collectors.toList());
        return childList;
    }

}
